package psn.kiko.interceptor;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import psn.kiko.constant.MessageConstant;
import psn.kiko.context.UserContext;
import psn.kiko.excepion.UserOperationException;
import psn.kiko.util.encrypt.Tokens;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户端--处理器拦截器
 */
@Component
@Slf4j
public class UserLoginHandlerInterceptor implements HandlerInterceptor{
	@Autowired
	Tokens tokens;
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
		String userToken=request.getHeader(tokens.getTokenProperties().getTokenName());
		boolean passed=tokens.validate(userToken);
		log.debug("user请求拦截:{} -- {}: validated ? {}",request.getMethod(),request.getRequestURI(),passed);
		if(passed){
			//token验证通过,将用户信息存入ThreadLocal
			Claims claims=tokens.getClaimsFrom(userToken);
			String userId=claims.getSubject();
			UserContext.setUserId(Integer.valueOf(userId));
			return passed;
		}else {
			//token验证失败,抛出异常
			throw new UserOperationException(MessageConstant.USER_LOGIN_EXPIRED);
		}
	}
}
